#!/usr/bin/env bash
# Copyright (c) 2016 Presto Labs Pte. Ltd.
# Author: leon

set -e

SCRIPT_REL_DIR="deploy"
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
DEPLOY_REL_DIR=".."
DEPLOY_DIR=$(realpath "${SCRIPT_DIR}/${DEPLOY_REL_DIR}/")
LOG_DIR=${SCRIPT_DIR}/log

printf "DEPLOY_DIR=${DEPLOY_DIR}\n"

# Changes working directory to the deployed directory.
cd "${DEPLOY_DIR}"

# Gets deploy profile.
source "${SCRIPT_REL_DIR}/profile"

# Git-ize the deployed directory.
set +o errexit
GIT_INITED=$(git rev-parse --is-inside-work-tree 2> /dev/null)
set -e
if [ "${GIT_INITED}" != "true" ]; then
  git init > /dev/null
  git config user.name "$(whoami)"
  git config user.email "$(whoami)@$(hostname -f)"
  git add .
  git commit -m "${DEPLOY_NAME}" --quiet
fi

# Adds cron entry.
if [ -f "${SCRIPT_DIR}/cron_profile" ]; then
  "${SCRIPT_DIR}/cron_tool" addsection \
    "${DEPLOY_NAME}" \
    "${SCRIPT_DIR}/cron_profile"
fi

# Makes symlink at ${RECENT_DIR}.
RECENT_DIR=${RECENT_DIR:=${HOME}/recent}
if [ ! -d "${RECENT_DIR}" ]; then
  mkdir -p "${RECENT_DIR}"
fi
TARGET="${RECENT_DIR}/${PACKAGE_NAME}"

# See more explanation about -sfT at this link: http://serverfault.com/a/522483
ln -sfT "${DEPLOY_DIR}" "${TARGET}"

# Leaves footprint.
if [ -f "RETIRED" ]; then
  rm "RETIRED"
fi
touch "BOOTSTRAPPED"
